package com.itheima.sfbx.insurance.service.impl;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.itheima.sfbx.framework.commons.exception.ProjectException;
import com.itheima.sfbx.framework.commons.utils.BeanConv;
import com.itheima.sfbx.insurance.dto.SafeguardVO;
import com.itheima.sfbx.insurance.enums.SafeguardEnum;
import com.itheima.sfbx.insurance.mapper.SafeguardMapper;
import com.itheima.sfbx.insurance.pojo.CategorySafeguard;
import com.itheima.sfbx.insurance.pojo.PlanSafeguard;
import com.itheima.sfbx.insurance.pojo.Safeguard;
import com.itheima.sfbx.insurance.service.ICategorySafeguardService;
import com.itheima.sfbx.insurance.service.IPlanSafeguardService;
import com.itheima.sfbx.insurance.service.ISafeguardService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Arrays;
import java.util.List;
import java.util.Set;
import java.util.stream.Collectors;

/**
 * @Description：保障项服务实现类
 */
@Slf4j
@Service
public class SafeguardServiceImpl extends ServiceImpl<SafeguardMapper, Safeguard> implements ISafeguardService {


    /**
     * 构建查询条件
     * @param safeguardVO
     */
    private LambdaQueryWrapper<Safeguard> queryWrapper(SafeguardVO safeguardVO) {
        LambdaQueryWrapper<Safeguard> lqw = new LambdaQueryWrapper<>();
        lqw.eq(StrUtil.isNotBlank(safeguardVO.getSafeguardKey()), Safeguard::getSafeguardKey,
                        safeguardVO.getSafeguardKey());
        lqw.like(StrUtil.isNotBlank(safeguardVO.getSafeguardKeyName()), Safeguard::getSafeguardKeyName,
                        safeguardVO.getSafeguardKeyName());
        lqw.eq(StrUtil.isNotBlank(safeguardVO.getDataState()), Safeguard::getDataState, safeguardVO.getDataState());
        return lqw;

    }

    /**
     *保障项分页查询
     * @param safeguardVO 保障项查询条件
     * @param pageNum 页码
     * @param pageSize 每页条数
     * @return
     */
    @Override
    public Page<SafeguardVO> findPage(SafeguardVO safeguardVO, int pageNum, int pageSize) {
        //分页查询，构建查询条件
        Page<Safeguard> page = new Page<>(pageNum, pageSize);
        LambdaQueryWrapper<Safeguard> lqw = queryWrapper(safeguardVO);
        Page<Safeguard> paged = this.page(page, lqw);
        return BeanConv.toPage(paged, SafeguardVO.class);
    }



    @Override
    public SafeguardVO findById(String safeguardId) {
        //TODO
        return null;
    }

    /**
     * 新增保险项
     * @param safeguardVO 保障项查询条件
     * @return
     */
    @Override
    @Transactional
    public SafeguardVO save(SafeguardVO safeguardVO) {
        Safeguard safeguard = BeanConv.toBean(safeguardVO, Safeguard.class);
        //保障项的key是不能重复的
        Integer count = this.lambdaQuery()
                .eq(Safeguard::getSafeguardKey, safeguardVO.getSafeguardKey())
                .count();
        if (count > 0) {
            throw new ProjectException(SafeguardEnum.SAVE_FAIL);
        }
        //如果不为空，就可以保存保障项了
        this.save(safeguard);
        return BeanConv.toBean(safeguard, SafeguardVO.class);
    }

    @Autowired
    private IPlanSafeguardService planSafeguardService;

    @Autowired
    private ICategorySafeguardService categorySafeguardService;

    /**
     * 修改保障项，若保障项关联了保险分类和保险方案
     * @param safeguardVO 保障项对象
     * @return
     */
    @Override
    @Transactional
    public Boolean update(SafeguardVO safeguardVO) {
        //查询保障项是否存在
        Safeguard safeguard = getById(safeguardVO.getId());
        if (safeguard == null){
            throw new ProjectException(SafeguardEnum.UPDATE_FAIL);
        }
        //查询当前保障项的key，不能被修改
        if (!safeguardVO.getSafeguardKey().equals(safeguard.getSafeguardKey())){
            //不等于就是已经修改
            throw new ProjectException(SafeguardEnum.UPDATE_FAIL);
        }
        //查询保障方案和保障分类，是否存在关系
        Integer count = planSafeguardService.lambdaQuery()
                .eq(PlanSafeguard::getSafeguardKey, safeguardVO.getSafeguardKey())
                .count();
        Integer count1 = categorySafeguardService.lambdaQuery()
                .eq(CategorySafeguard::getSafeguardKey, safeguardVO.getSafeguardKey())
                .count();
        if (count > 0 || count1 > 0) {
            throw new ProjectException(SafeguardEnum.UPDATE_FAIL);
        }
        //可以修改了
        Safeguard bean = BeanConv.toBean(safeguardVO, Safeguard.class);
        bean.setUpdateTime(null);
        bean.setUpdateBy(null);
        return this.updateById(bean);
    }


    /**
     * 删除保障项，也许判断保障项是否已经关联了关系
     * @param checkedIds 选择中对象Ids
     * @return
     */
    @Override
    @Transactional
    public Boolean delete(String[] checkedIds) {
        //先将字符串集合转成list集合
        List<String> ids = Arrays.asList(checkedIds);
        //将数据从列表中查询出来
        List<Safeguard> safeguardList = listByIds(ids);
        if (CollUtil.isEmpty(safeguardList)){
            return true;
        }
        //将所有的key取出来
        Set<String> keySet = safeguardList.stream().map(Safeguard::getSafeguardKey).collect(Collectors.toSet());
        Integer count = planSafeguardService.lambdaQuery()
                .in(PlanSafeguard::getSafeguardKey, keySet)
                .count();
        Integer count1 = categorySafeguardService.lambdaQuery()
                .in(CategorySafeguard::getSafeguardKey, keySet)
                .count();
        if (count > 0 || count1 > 0) {
            throw new ProjectException(SafeguardEnum.DEL_FAIL);
        }
        return removeByIds(ids);
    }

    /**
     * 查询保障项列表
     * @param safeguardVO 查询条件
     * @return
     */
    @Override
    public List<SafeguardVO> findList(SafeguardVO safeguardVO) {
        //构建查询条件
        LambdaQueryWrapper<Safeguard> lqw = queryWrapper(safeguardVO);
        List<Safeguard> voList = this.list(lqw);
        return BeanConv.toBeanList(voList, SafeguardVO.class);
    }


    @Override
    public List<SafeguardVO> findShowPageItemByKey(List<String> safeguardKeyList) {
        //TODO
        return null;
    }

    @Override
    public SafeguardVO findBySafeguardKey(String safeguardKey) {
        //TODO
        return null;
    }
}
